﻿using System;
using System.Drawing;
using System.Collections.Generic;
using System.Text;
using ZXing;
using ZXing.Common;
using System.IO;
using System.Runtime.InteropServices;
using System.Reflection;
using System.ComponentModel;

namespace OdooRpcClient.Converters
{
    public class Helper
    {
        public static Type GetClassByClassFullType(string fullType)
        {
            Assembly assembly = Assembly.Load("OdooRpcClient"); //程序集名称
            //从程序集中获取指定对象类型;
            Type type = assembly.GetType(fullType); //程序集名称.类名
            return type;
        }

       

        public static string GenerateBarcodeString(string barcodeValue, int height, int width)
        {
            try
            {
                if (barcodeValue != null)
                {
                    // 1.设置条形码规格
                    EncodingOptions encodeOption = new EncodingOptions();

                    encodeOption.Height = MillimetersToPixelsWidth(height); // 必须制定高度、宽度(像素)
                    encodeOption.Width = MillimetersToPixelsWidth(width);
                    encodeOption.PureBarcode = false; // 是否是纯码，如果为 false，则会在图片下方显示数字


                    // 2.生成条形码图片
                    BarcodeWriter wr = new BarcodeWriter();
                    wr.Options = encodeOption;
                    wr.Format = BarcodeFormat.CODE_128;  // 这里可以设定条码的标准
                    Bitmap img = wr.Write(barcodeValue); // 生成图片

                    // 3. 转Base64
                    MemoryStream ms = new MemoryStream();
                    img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                    byte[] arr = new byte[ms.Length]; ms.Position = 0;
                    ms.Read(arr, 0, (int)ms.Length); ms.Close();
                    return Convert.ToBase64String(arr);
                }
                else
                {
                    return null;
                }
            }
            catch
            {
                return null;
            }
        }

        [DllImport("gdi32.dll")]
        private static extern int GetDeviceCaps(IntPtr hdc, int Index);

        public static int MillimetersToPixelsWidth(double length)
        {
            System.Windows.Forms.Panel p = new System.Windows.Forms.Panel();
            System.Drawing.Graphics g = System.Drawing.Graphics.FromHwnd(p.Handle);
            IntPtr hdc = g.GetHdc();
            int width = GetDeviceCaps(hdc, 4);     // HORZRES 
            int pixels = GetDeviceCaps(hdc, 8);     // BITSPIXEL
            g.ReleaseHdc(hdc);
            return Convert.ToInt32((((double)pixels / (double)width) * (double)length));
        }
    }
}
